package org.example.todo.service;

import org.example.todo.dao.TodoRepository;
import org.example.todo.entity.TodoEntity;
import org.example.todo.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class TodoServiceImpl implements TodoService {
    @Autowired
    private TodoRepository todoRepository;

    @Override
    public Result<List<TodoEntity>> queryAll() {
        List<TodoEntity> all = todoRepository.findAll();
        return Result.ok(all);
    }

    @Override
    public Result<TodoEntity> queryById(Long id) {
        Optional<TodoEntity> byId = todoRepository.findById(id);
        return Result.ok(byId.orElse(null));
    }

    @Override
    public Result<?> addTodo(TodoEntity todoEntity) {
        TodoEntity save = todoRepository.save(todoEntity);
        return Result.ok();
    }

    @Override
    public Result<?> deleteTodo(Long id) {
        todoRepository.deleteById(id);
        return Result.ok();
    }

    @Override
    public Result<?> updateTodo(TodoEntity todoEntity) {
        if (todoEntity.getId() == null) {
            return Result.fail("update todo needs id.");
        }
        todoRepository.save(todoEntity);
        return Result.ok();
    }
}
